import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import type { AppRouteObject } from "./routes";

interface AuthGuardProps {
  children: React.ReactNode;
  route: AppRouteObject;
}

const AuthGuard: React.FC<AuthGuardProps> = ({ children, route }) => {
  const location = useLocation();

  // 这里可以添加您的认证逻辑
  const isAuthenticated = localStorage.getItem("token") !== null;

  if (route.meta?.requiresAuth && !isAuthenticated) {
    // 如果需要认证但未登录，重定向到登录页
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  if (!route.meta?.requiresAuth && isAuthenticated) {
    // 如果已登录但访问登录页，重定向到首页
    return <Navigate to="/" replace />;
  }

  return <>{children}</>;
};

export default AuthGuard;
